package com.csii.adhoc.dataunits.service;

import com.csii.adhoc.dataready.TDataCondPo;

import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DataUnitUtils {

    /*
     将所有数据库表中带下划线的字段改成 大写 例如：SECOND_NAME 改成 secondName
     */
    public static String camelSqlFieldName(String fieldName) {

        if (fieldName == null || "".equals(fieldName) || "".equals(fieldName.trim())) {
            return fieldName;
        }
        String keyLowerCase = fieldName.toLowerCase(Locale.ROOT);
        StringBuffer keyChanged = new StringBuffer();
        Pattern p = Pattern.compile("_[a-z|A-Z]");
        Matcher m = p.matcher(keyLowerCase);
        while (m.find()) {
            m.appendReplacement(keyChanged, "_" + m.group().toUpperCase());
        }
        m.appendTail(keyChanged);
        return keyChanged.toString().replaceAll("_", "");
    }

    /*
    当 createBy 为这种形式时，转成数据库的字段形式 CREATE_BY
 */
    public static String deCamelCase(String str) {
        /*
         将所有前端发过来的java Pojo 命名转为数据库字段大小写不敏感命名 例如：secondName 转为 SECOND_NAME
         否则数据库将报错
         */
        if (str == null || "".equals(str) || "".equals(str.trim())) {
            return str;
        }
        //定义变量用于返回
        String retString = "";

        String strA = "";
        Pattern p = Pattern.compile("[A-Z]");
        Matcher m = p.matcher(str);
        while (m.find()) {
            //每一轮取单个大写字母
            String singleStr = m.group();
            //取索引
            int charsIndex = 0;
            char c = singleStr.toCharArray()[0];
            char[] chars = str.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                if (chars[i] == c) {
                    charsIndex = i;
                    break;
                }
            }
            //开始拆分两段
            strA = str.substring(0, charsIndex + 1);
            str = str.substring(charsIndex + 1, chars.length);
            // 将大写字母 "A" 替换为 "_A"
            strA = strA.replaceFirst(singleStr, "_" + singleStr);
            retString = retString + strA.toUpperCase(Locale.ROOT);

        }
        //将未处理的字串尾部添加到返回字串中
        retString = retString + str.toUpperCase(Locale.ROOT);
        return retString;
    }

    /*
        生成32位无小短线的 uuid
     */
    public static String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    //将 树形条件list 转为 sql where 条件组
    public static String combineSqlWhere(List<TDataCondPo> list) {
        String sql = "";
        //先进行排序
        if (list.size() > 1) {
            Collections.sort(list);
        }
        //再进行拼装
        for (TDataCondPo tDataCondPo : list) {
            //异常判断
            if (tDataCondPo.getModelId() == null) {
                continue;
            }
            //String condOper = tDataCondPo.getCondType();
            String condOper = "and";
            String leftField = tDataCondPo.getFldEnname();

            //将前端驼峰命名转成数据库的字段名
            leftField = DataUnitUtils.deCamelCase(leftField);
            String operator = tDataCondPo.getCondOper();
            String rightValue = tDataCondPo.getValue() == null || "".equals(tDataCondPo.getValue()) || "".equals(tDataCondPo.getValue().trim()) ? "" : tDataCondPo.getValue();
            String rightValue2 = tDataCondPo.getAssist() == null || "".equals(tDataCondPo.getAssist()) || "".equals(tDataCondPo.getAssist().trim()) ? "" : tDataCondPo.getAssist();
            String value = "";
            if (!((leftField == null || "".equals(leftField.trim())) | (condOper == null || "".equals(condOper.trim())) | (rightValue == null || "".equals(rightValue.trim())) | (rightValue == null || "".equals(rightValue.trim())))) {
                // 操作符类型还原，即由 0 = ,1 > ,2 < ,3 >= ,4 <=,5 <> ,6 like ,7 in ,8 x>n and x<n, 9 x>=n and x<n ,10 x>n and x<=n ,11 x>=n and x<=n
                switch (operator) {
                    case "0":
                        // 0 =
                        operator = "=";
                        value = "\"" + leftField + "\"" + " " + operator + "'" + rightValue + "'";
                        break;
                    case "1":
                        // 1 >
                        operator = ">";
                        value = "\"" + leftField + "\"" + " " + operator + "'" + rightValue + "'";
                        break;
                    case "2":
                        //2 <
                        operator = "<";
                        value = "\"" + leftField + "\"" + " " + operator + "'" + rightValue + "'";
                        break;
                    case "3":
                        //3 >=
                        operator = ">=";
                        value = "\"" + leftField + "\"" + " " + operator + "'" + rightValue + "'";
                        break;
                    case "4":
                        //4 <=
                        operator = "<=";
                        value = "\"" + leftField + "\"" + " " + operator + "'" + rightValue + "'";
                        break;
                    case "5":
                        //5 <>
                        operator = "<>";
                        value = "\"" + leftField + "\"" + " " + operator + "'" + rightValue + "'";
                        break;
                    case "6":
                        //6 like
                        operator = " like ";
                        value = "\"" + leftField + "\"" + " " + operator + "'%" + rightValue + "%'";
                        break;
                    case "7":
                        //7 in
                        operator = " in ";
                        rightValue = rightValue.trim();
                        String[] strs = rightValue.split(",");
                        StringBuffer sb = new StringBuffer();
                        for (int x = 0; x < strs.length; x++) {
                            String str = strs[x];
                            if (x != strs.length - 1) {
                                sb.append("'").
                                        append(str.replaceAll("'|\"", ""))
                                        .append("'")
                                        .append(",");
                            } else {
                                sb.append("'").
                                        append(str.replaceAll("'|\"", ""))
                                        .append("'");
                            }
                        }

                        value = "\"" + leftField + "\"" + " " + operator + "(" + sb.toString() + ")";
                        break;
                    case "8":
                        //8 x>n and x<n,
                        value = "\"" + leftField + "\"" + " " + " > " + "'" + rightValue + "'" + " and " +
                                "\"" + leftField + "\"" + " " + " < " + "'" + rightValue2 + "'";
                        break;
                    case "9":
                        // 9 x>=n and x<n
                        value = "\"" + leftField + "\"" + " " + " >= " + "'" + rightValue + "'" + " and " +
                                "\"" + leftField + "\"" + " " + " < " + "'" + rightValue2 + "'";
                        break;
                    case "10":
                        // 10 x>n and x<=n
                        value = "\"" + leftField + "\"" + " " + " > " + "'" + rightValue + "'" + " and " +
                                "\"" + leftField + "\"" + " " + " <= " + "'" + rightValue2 + "'";
                        break;
                    case "11":
                        // 11 x>=n and x<=n
                        value = "\"" + leftField + "\"" + " " + " >= " + "'" + rightValue + "'" + " and " +
                                "\"" + leftField + "\"" + " " + " <= " + "'" + rightValue2 + "'";
                        break;
                    default: {
                        System.out.println("条件筛选case异常！ operator：" + operator);
                    }
                }

            }

            List<TDataCondPo> children = tDataCondPo.getChildren();
            int childNum = children == null ? 0 : children.size();
            if (children != null) {
                String subValue = combineSqlWhere(children);
                condOper = children.size() == 0 ? "or" : "and";
                if ("".equals(sql)) {
                    sql = sql + subValue;
                } else {
                    sql = sql + ("".equals(subValue) ? "" : " " + condOper + " (" + subValue + ")");
                }
            }

            //拼装 where 条件
            if ("".equals(sql)) {
                sql = sql + value;
            } else {
                if ("and".equals(condOper)) {
                    sql = sql + ("".equals(value) ? "" : " " + condOper + " " + value);
                    //sql = sql + ;
                } else {
                    sql = "(" + sql + ")" + ("".equals(value) ? "" : " " + condOper + " " + value);
                }

            }
        }
        return sql;
    }

    /**
     * @param word
     * @return
     * @description 判断当前字符串是否全为大写
     */
    public static boolean isAcronym(String word) {
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (Character.isLowerCase(c)) {
                return false;
            }
        }
        return true;
    }

    public static boolean isUpperCase(String word) {
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (Character.isLowerCase(c)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 验证 正则表达式
     *
     * @return boolean
     * @author regex 正则表达式 value 所属字符串
     */
    public static boolean regex(String regex, String value) {
        Pattern p = Pattern.compile(regex);
        Matcher m = p.matcher(value);
        return m.find();
    }
}
